package com.wjerp.tplus.server.common.security;

import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.domain.entity.CompanyInfo;
import com.wjerp.tplus.server.domain.entity.sys.UserInfo;
import com.wjerp.tplus.server.domain.service.CompanyService;
import com.wjerp.tplus.server.domain.service.UserInfoService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author lishuailei
 */
@Component
public class JwtPlatformUserInfoServiceImpl implements UserDetailsService {
	
	@Resource
	private UserInfoService userInfoService;

	@Resource
	private CompanyService companyService;
	
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    	UserInfo userInfo = userInfoService.findByMobileOrEmail(username);
    	try{
    		List<String> roles= userInfoService.findUserPermissionByDisplayUserIdAndUserType(userInfo.getDisplayUserId(),userInfo.getUserType());
    		if (userInfo == null) {
                throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
            } else {
				CompanyInfo companyInfo = companyService.loadCompanyInfoByUserCode(userInfo.getDisplayUserId());
				UserDetails u = JwtUserFactory.create(userInfo,roles,companyInfo.getCompanyCode());
                return u;
            }
    	}catch(BusinessException e){
    		throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    	}        
    }
}

